package Circle::Common;

use 5.006;
use strict;
use warnings;
use Exporter 'import';
use LWP::UserAgent;
use HTTP::Request;
use Slurp;
use Try::Tiny;
use YAML;
use JSON;
use Carp;

our @EXPORT_OK = qw(
    load_config
    http_json_post
    http_json_get
    );

my $config  = undef;
sub load_config {
    if ($config) {
        return $config;
    }

    my $config = {};
    try {
        my $content = slurp('./lib/Circle/config.yml');
        $config = Load($content);
    } catch {
        carp "cannot load config, error: $_";
    };
    return $config;
}

sub get_session_key {
    my $config = load_config();
    my $user = $config->{user};
    my $home = $ENV{HOME};
    my $session_path = $user->{sessionPath};
    my $file_path = "${home}/${session_path}";
    try {
        my @lines = slurp($file_path);
        my @session_keys = grep { chomp($_); $_ =~ /^sessionKey/; } @lines;
        if (@session_keys > 0) {
            my $session_key = $session_keys[0];
            $session_key =~ s/sessionKey=//;
            return $session_key;
        }
    } catch {
        carp "cannot read $session_path, error: $_";
    };

    return;
}

sub http_json_post {
    my ($url, $data) = @_;
    my $config = load_config();
    my $http = $config->{http};
    my $session_key = get_session_key();
    my $ua = LWP::UserAgent->new();
    $ua->timeout($http->{timeoutWrite});
    my $header;
    if ($session_key) {
        $header = [
            'AuthorizationV2' => $session_key,
            'Content-Type' => 'application/json; charset=UTF-8'
            ];
    } else {
        $header = ['Content-Type' => 'application/json; charset=UTF-8'];
    }
    my $request = HTTP::Request->new('POST', $url, $header, encode_json($data));
    my $response = $ua->request($request);
    if ($response->is_success) {
        return decode_json($response->decoded_content);
    }
    else {
        carp 'http_json_post' . $response->status_line ? $response->status_line : 'unknown';
        die $response->status_line;
    }
}

sub http_json_get {
    my ($url) = @_;
    my $config = load_config();
    my $http = $config->{http};
    my $session_key = get_session_key();
    my $ua = LWP::UserAgent->new();
    $ua->timeout($http->{timeoutRead});
    my $header;
    if ($session_key) {
        $header = [
            'AuthorizationV2' => $session_key,
            'Content-Type' => 'application/json; charset=UTF-8'
            ];
    } else {
        $header = ['Content-Type' => 'application/json; charset=UTF-8'];
    }
    my $request = HTTP::Request->new('GET', $url, $header);
    my $response = $ua->request($request);
    if ($response->is_success) {
        return decode_json($response->decoded_content);
    }
    else {
        carp 'http_json_get' . $response->status_line ? $response->status_line : 'unknown';
        die $response->status_line;
    }
}



1;
